import pandas as pd
import geopandas as gpd

import folium
from folium import Choropleth
from folium.plugins import HeatMap

from learntools.core import binder
binder.bind(globals())
from learntools.geospatial.ex3 import *

우리는 대화형 맵을 표시하기 위한 함수 'embed_map()'을 정의한다. 맵을 포함하는 변수와 맵을 저장할 HTML 파일의 이름이라는 두 가지 인수를 사용할 수 있습니다.

이 기능은 [모든 웹 브라우저에서] 지도를 볼 수 있도록 합니다(https://github.com/python-visualization/folium/issues/812).

def embed_map(m, file_name):
    from IPython.display import IFrame
    m.save(file_name)
    return IFrame(file_name, width='100%', height='500px')

1) 지진은 판 경계와 일치합니까?

아래의 코드 셀을 실행하여 글로벌 플레이트 경계를 표시하는 DataFrame 'plate_boundaries'를 생성하십시오. 좌표 열은 경계를 따라 (위도, 경도) 위치 목록입니다.

plate_boundaries = gpd.read_file("data/Plate_Boundaries/Plate_Boundaries/Plate_Boundaries.shp")
plate_boundaries['coordinates'] = plate_boundaries.apply(lambda x: [(b,a) for (a,b) in list(x.geometry.coords)], axis='columns')
plate_boundaries.drop('geometry', axis=1, inplace=True)

plate_boundaries.head()
HAZ_PLATES HAZ_PLAT_1 HAZ_PLAT_2 Shape_Leng coordinates
0 TRENCH SERAM TROUGH (ACTIVE) 6722 5.843467 [(-5.444200361999947, 133.6808931800001), (-5....
1 TRENCH WETAR THRUST 6722 1.829013 [(-7.760600482999962, 125.47879802900002), (-7...
2 TRENCH TRENCH WEST OF LUZON (MANILA TRENCH) NORTHERN ... 6621 6.743604 [(19.817899819000047, 120.09999798800004), (19...
3 TRENCH BONIN TRENCH 9821 8.329381 [(26.175899215000072, 143.20620700100005), (26...
4 TRENCH NEW GUINEA TRENCH 8001 11.998145 [(0.41880004000006466, 132.8273013480001), (0....

그런 다음 변경 없이 아래의 코드 셀을 실행하여 과거 지진 데이터를 데이터 프레임 "지진"에 로드합니다.

earthquakes = pd.read_csv("data/earthquakes1970-2014.csv", parse_dates=["DateTime"])
earthquakes.head()
DateTime Latitude Longitude Depth Magnitude MagType NbStations Gap Distance RMS Source EventID
0 1970-01-04 17:00:40.200 24.139 102.503 31.0 7.5 Ms 90.0 NaN NaN 0.0 NEI 1.970010e+09
1 1970-01-06 05:35:51.800 -9.628 151.458 8.0 6.2 Ms 85.0 NaN NaN 0.0 NEI 1.970011e+09
2 1970-01-08 17:12:39.100 -34.741 178.568 179.0 6.1 Mb 59.0 NaN NaN 0.0 NEI 1.970011e+09
3 1970-01-10 12:07:08.600 6.825 126.737 73.0 6.1 Mb 91.0 NaN NaN 0.0 NEI 1.970011e+09
4 1970-01-16 08:05:39.000 60.280 -152.660 85.0 6.0 ML 0.0 NaN NaN NaN AK NaN

아래의 코드 셀은 지도에서 플레이트 경계를 시각화합니다. 지진 데이터를 모두 사용하여 동일한 지도에 열 지도를 추가하고 지진이 플레이트 경계와 일치하는지 여부를 확인합니다.

m_1 = folium.Map(location=[35,136], tiles='cartodbpositron', zoom_start=5)
for i in range(len(plate_boundaries)):
    folium.PolyLine(locations=plate_boundaries.coordinates.iloc[i], weight=2, color='black').add_to(m_1)

# Your code here: Add a heatmap to the map
HeatMap(data=earthquakes[['Latitude', 'Longitude']], radius=15).add_to(m_1)

# Get credit for your work after you have created a map
q_1.a.check()

# Show the map
m_1

Thank you for creating a map!

Make this Notebook Trusted to load map: File -> Trust Notebook

그렇다면, 위의 지도를 볼 때, 지진은 판 경계와 일치할까요?

q_1.b.solution()

Solution: Yes, earthquakes coincide with plate boundaries.

2) 일본에서는 지진의 깊이와 판 경계에 대한 근접성 사이에 관계가 있습니까?

당신은 최근에 지진의 깊이가 우리에게 지구의 구조에 대한 중요한 정보를 알려준다는 것을 읽었습니다. 여러분은 흥미로운 세계적 패턴이 있는지 알고 싶으실 겁니다. 그리고 일본에서는 깊이가 어떻게 다른지 알고 싶으실 겁니다.

m_2 = folium.Map(location=[35,136], tiles='cartodbpositron', zoom_start=5)
for i in range(len(plate_boundaries)):
    folium.PolyLine(locations=plate_boundaries.coordinates.iloc[i], weight=2, color='black').add_to(m_2)
    
# Your code here: Add a map to visualize earthquake depth
def color_producer(val):
    if val < 50:
        return 'forestgreen'
    elif val < 100:
        return 'darkorange'
    else:
        return 'darkred'

for i in range(0,len(earthquakes)):
    folium.Circle(
        location=[earthquakes.iloc[i]['Latitude'], earthquakes.iloc[i]['Longitude']],
        radius=2000,
        color=color_producer(earthquakes.iloc[i]['Depth'])).add_to(m_2)

# Get credit for your work after you have created a map
q_2.a.check()

# View the map
m_2

Thank you for creating a map!

Make this Notebook Trusted to load map: File -> Trust Notebook

플레이트 경계에 대한 근접성과 지진 깊이 사이의 관계를 탐지할 수 있습니까? 이 패턴이 전체적으로 유지됩니까? 일본에서요?

q_2.b.solution()

Solution: In the northern half of Japan, it does appear that earthquakes closer to plate boundaries tend to be shallower (and earthquakes farther from plate boundaries are deeper). This pattern is repeated in other locations, such as the western coast of South America. But, it does not hold everywhere (for instance, in China, Mongolia, and Russia).

3) 인구밀도가 높은 현은 어디입니까?

다음 코드 셀(변경 없이)을 실행하여 일본 현의 지리적 경계를 포함하는 GeoDataFrame '현'을 만듭니다.

prefectures = gpd.read_file("data/japan-prefecture-boundaries/japan-prefecture-boundaries/japan-prefecture-boundaries.shp")
prefectures.set_index('prefecture', inplace=True)
prefectures.head()
geometry
prefecture
Aichi MULTIPOLYGON (((137.09523 34.65330, 137.09546 ...
Akita MULTIPOLYGON (((139.55725 39.20330, 139.55765 ...
Aomori MULTIPOLYGON (((141.39860 40.92472, 141.39806 ...
Chiba MULTIPOLYGON (((139.82488 34.98967, 139.82434 ...
Ehime MULTIPOLYGON (((132.55859 32.91224, 132.55904 ...

다음 코드셀은 일본 각 도도부현의 인구, 면적(제곱킬로미터), 인구밀도(제곱킬로미터당)를 포함하는 데이터 프레임 '통계'를 생성한다. 코드 셀을 변경하지 않고 실행합니다.

population = pd.read_csv("data/japan-prefecture-population.csv")
population.set_index('prefecture', inplace=True)

# Calculate area (in square kilometers) of each prefecture
area_sqkm = pd.Series(prefectures.geometry.to_crs(epsg=32654).area / 10**6, name='area_sqkm')
stats = population.join(area_sqkm)

# Add density (per square kilometer) of each prefecture
stats['density'] = stats["population"] / stats["area_sqkm"]
stats.head()
population area_sqkm density
prefecture
Tokyo 12868000 1800.614782 7146.448049
Kanagawa 8943000 2383.038975 3752.771186
Osaka 8801000 1923.151529 4576.342460
Aichi 7418000 5164.400005 1436.372085
Saitama 7130000 3794.036890 1879.264806

다음 코드 셀을 사용하여 모집단 밀도를 시각화하는 맥락막 맵을 만듭니다.

m_3 = folium.Map(location=[35,136], tiles='cartodbpositron', zoom_start=5)

# Your code here: create a choropleth map to visualize population density
Choropleth(geo_data=prefectures['geometry'].__geo_interface__,
           data=stats['density'],
           key_on="feature.id",
           fill_color='YlGnBu',
           legend_name='Population density (per square kilometer)'
          ).add_to(m_3)

# Get credit for your work after you have created a map
q_3.a.check()
# View the map
# embed_map(m_3, 'q_3.html')
# m_3

Thank you for creating a map!

어느 세 개의 현이 다른 현보다 상대적으로 밀도가 높습니까? 그들은 전국에 퍼져 있는가, 아니면 거의 같은 지리적 지역에 위치해 있는가? (일본 지리에 익숙하지 않은 경우 이 지도가 질문에 답하는 데 유용할 수 있습니다.

q_3.b.solution()

Solution: Tokyo, Kanagawa, and Osaka have the highest population density. All of these prefectures are located in central Japan, and Tokyo and Kanagawa are adjacent.

4) 고밀도 현 중 규모 지진이 발생하기 쉬운 현은 어디입니까?

지진 보강의 혜택을 받을 수 있는 하나의 현을 제안하기 위한 지도를 만듭니다. 지도는 밀도와 지진 규모를 모두 시각화해야 한다.

m_4 = folium.Map(location=[35,136], tiles='cartodbpositron', zoom_start=5)

# Your code here: create a map
def color_producer(magnitude):
    if magnitude > 6.5:
        return 'red'
    else:
        return 'green'

Choropleth(
    geo_data=prefectures['geometry'].__geo_interface__,
    data=stats['density'],
    key_on="feature.id",
    fill_color='BuPu',
    legend_name='Population density (per square kilometer)').add_to(m_4)

for i in range(0,len(earthquakes)):
    folium.Circle(
        location=[earthquakes.iloc[i]['Latitude'], earthquakes.iloc[i]['Longitude']],
        popup=("{} ({})").format(
            earthquakes.iloc[i]['Magnitude'],
            earthquakes.iloc[i]['DateTime'].year),
        radius=earthquakes.iloc[i]['Magnitude']**5.5,
        color=color_producer(earthquakes.iloc[i]['Magnitude'])).add_to(m_4)

# Get credit for your work after you have created a map
q_4.a.check()

# View the map
# m_4

Thank you for creating a map!

추가 지진 보강을 위해 어느 현을 추천하십니까?

q_4.b.solution()

Solution: While there's no clear, single answer to this question, there are a few reasonable options. Tokyo is by far the most densely populated prefecture and has also experienced a number of earthquakes. Osaka is relatively less densely populated, but experienced an earthquake that was relatively stronger than those near Tokyo. And, the long coast of Kanagawa (in addition to its high density and the historical proximity of strong earthquakes) might lead us to worry about the added potential tsunami risk.

Keep going

Learn how to convert names of places to geographic coordinates with geocoding. You'll also explore special ways to join information from multiple GeoDataFrames.